<template>
  <div id="app">
    <div class="users">
      <span
        v-for="user in users"
        :key="user.userId"
        class="user"
        :class="{ selected: user.userId === selectedUser }"
        @click="selectUser(user.userId)"
      >
        <img
          src="\head04.png"
          alt="User avatar"
          class="uhead"
        >
        <span class="uname">{{ user.nickName }}</span>
      </span>
    </div>
    <div
      v-if="selectedUser"
      class="chat"
    >
      <div class="vback">
        <div class="container">
          <!-- 聊天记录 -->
          <div class="chat-history">
            <div
              v-for="(item, index) in chatHistory"
              :key="index"
              :class="{
                'message-left': item.From === 0,
                'message-right': item.From === 1,
              }"
            >
              <div
                class="message"
                :class="{
                  'message-left': item.From === 0,
                  'message-right': item.From === 1,
                }"
              >
                {{ item.Message }}
              </div>
              <img
                :src="item.avatar"
                class="avatar"
              >
            </div>
          </div>

          <div class="chat-input">
            <button
              class="end"
              @click="close"
            >
              结束
            </button>
            <textarea
              v-model="message"
              placeholder=""
              @keyup.enter="sendMessage"
            />
            <button @click="sendMessage">
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { WebSocketBean } from 'tools-vue3'
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

const message = ref('')
const route = useRoute()
const users = ref([])

const getCookie = (name) => {
  const value = '; ' + document.cookie
  const parts = value.split('; ' + name + '=')
  if (parts.length === 2) return parts.pop().split(';').shift()
}
const shopid = getCookie('shopid')
const MessageType = {
  Get: 0,
  Send: 1,
  Message: 2
}

const selectedUser = ref(null) // 添加这一行来存储当前选定的用户
watch(selectedUser, (newValue, oldValue) => {
  // 这里可以执行任何你需要的逻辑
  conf.send.Data.UserId = newValue
})
const selectUser = (userId) => {
  selectedUser.value = userId // 更新选定的用户
  conf.UserId = userId
  console.log(selectedUser.value)
  console.log(conf.UserId)
  gethistory() // 获取与选定用户的聊天历史
}
const conf = reactive({
  status: '未连接',
  messagetype: {
    [MessageType.Get]: '收到',
    [MessageType.Send]: '发送',
    [MessageType.Message]: '通知'
  },
  message: [],
  url: `ws://127.0.0.1:8001/ws?token=${shopid}`,
  send: {
    Time: '',
    Data: {
      Email: '',
      Username: '',
      UserId: selectedUser.value,
      Shopid: shopid,
      message: '',
      From: '1'
    }
  }
})
const fetchusers = () => {
  http.request({
    url: 'http://localhost:8086/msg/GetUserList',
    method: 'GET'
  })
    .then(({ data }) => {
      users.value = data
    })
}

const getParam = () => {
  return {
    url: conf.url,
    needReconnect: true,
    reconnectGapTime: 5000,
    heartSend: '~',
    heartGet: '~',
    heartGapTime: 5000,
    onopen: () => {},
    onmessage: (data) => {
      const sp = JSON.parse(data.data)
      chatserve.push({ Time: new Date().getTime() * 0.001, From: 0, userId: sp.data.UserId, Message: sp.data.message, Shopid: sp.data.Shopid })
      console.log(chatserve)
      chatHistory.value.push({
        From: 0,
        avatar: '\\head04.png',
        Message: `${sp.data.message}`
      })
    },
    onerror: () => {}
  }
}

const chatHistory = ref([])
const ws = new WebSocketBean(getParam())
const chatserve = []

const start = () => {
  ws.start(getParam())
  ws.status = 1
}

const close = () => {
  http.request({
    url: 'http://localhost:8086/msg/save',
    method: 'POST',
    data: chatserve
  })
  ws.dispose()
  alert('关闭连接成功')
}

const gethistory = () => {
  http.request({
    url: 'http://localhost:8086/msg/GetByUserIdAndShopId',
    method: 'POST',
    data: { userId: selectedUser.value, Shopid: shopid }
  })
    .then(({ data }) => {
      data.forEach(item => {
        if (item.From === 0) {
          item.avatar = '\\head04.png'
        } else if (item.From === 1) {
          item.avatar = '\\logo.png'
        }
      })
      console.log(data)
      chatHistory.value = data
    })
}

const sendMessage = () => {
  conf.send.Data.message = message.value
  if (message.value === '' || message.value === '\n') {
    alert('消息不能为空')
  } else if (ws.status === 1) {
    const sendStatus = ws.send(conf.send)

    if (sendStatus) {
      console.log(conf.send)
      console.log('success')
      chatserve.push({ Time: new Date().getTime() * 0.001, From: 1, userId: selectedUser.value, Message: conf.send.Data.message, Shopid: shopid })
      chatHistory.value.push({
        From: 1,
        avatar: '\\logo.png',
        Message: `${message.value}`
      })
      message.value = ''
    }
  } else {
    alert('未连接')
  }
}

start()
fetchusers()
</script>

<style scoped lang="scss">
.user.selected {
  background-color: rgb(144, 210, 252);
}
.end{
  margin-right:10px;
}
.users{
   white-space: nowrap; /* 防止用户换行 */
  overflow-x: auto; /* 当内容溢出时显示滚动条 */
}
.user {
  display: inline-block;
  text-align: center; /* 让图片和文字居中对齐 */
  margin-right: 20px; /* 添加右边距，使得用户间有一些间距 */
  cursor: pointer;
}
.vback {
  height: 720px;
  background-color: rgb(236, 235, 235);
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  padding-top: 20px;
  background-color: rgb(236, 235, 235);
  overflow: auto;
}
.uhead {
  display: block;
  width: 50px; /* 调整图片大小 */
  height: 50px;
  object-fit: cover; /* 保持图片比例 */
  vertical-align: middle; /* 垂直居中 */
  margin: 0 auto; /* 让图片在其容器中居中 */
}

.uname {
  display: block;
  font-size: 20px; /* 调整文字大小 */
  vertical-align: middle; /* 垂直居中 */
}

/* 让图片和文字水平居中 */
span {
width:100px;
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}
.chat-history {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.message-left,
.message-right {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.message-left .message,
.message-right .message {
  padding: 10px;
  border-radius: 10px;
  max-width: 70%;
}

.message-left .message {
  background-color: rgb(255, 255, 255);
  color: black;
  order: 1;
  text-align: left;
}

.message-right .message {
  background-color: rgb(0, 133, 250);
  color: white;
  order: -1;
  text-align: left;
}

.message-right {
  justify-content: flex-end;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin: 0 10px;
}

.message-right .avatar {
  order: 1;
}

.chat-input {
  width:1750px;
  display: flex;
  align-items: center;
  position: fixed;
  bottom: 0;
  right: 0; /* 修改这一行 */
  height: 40px;
  margin-bottom: 5px;
  /* 增加底部高度 */
  background-color: #ffffff;
  padding: 10px 10px;
  /* 减小框的高度 */
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
  border-color: white;
  margin-left: auto; /* 添加这一行 */
  margin-right:23px;
}

.chat-input textarea {
  flex: 1;
  margin-right: 10px;
  height: 30px;
  background-color: #f0f0f0;
  border: none;
}

.chat-input button {
  background-color: rgb(0, 124, 248);
  color: #fff;
  padding: 5px 10px;
  margin-bottom: 0px;
  border-radius: 5px;
  height: 30px;
  font-size: 15px;
  line-height: 20px;
};
</style>
